package M
{
	import flash.events.*;
	import flash.net.*;
	import flash.text.TextField;
	import flash.utils.*;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.controls.RichTextEditor;
	import mx.controls.TextArea;
	
	public class AllTranslate
	{
		private var ts:Translate;
		private var docName:String;
		
		private var currentNum:int;		
		private var korText:TextField = new TextField;
		private var tempRich:RichTextEditor = new RichTextEditor();
		private var field:TextField = new TextField();
		
		private var myData:ArrayCollection;
		private var myData2:ArrayCollection;
		
		private var wordArray:ArrayCollection
		private var wl:WordLocation;
		
		private var doc:XML;
		private var ip:String;
		
		private var i:int;
		private var j:int;
		 
		public function AllTranslate(ts:Translate)
		{
			this.ts = ts;
			this.docName = ts.documentName;
			this.myData = ts.myData;
			this.myData2 = ts.myData2;
			this.ip = ts.ip;
		}
		
        public function start():void {   
        	
        	var loader:URLLoader = new URLLoader();
   			loader.dataFormat = URLLoaderDataFormat.TEXT;
   			loader.addEventListener(Event.COMPLETE, handleCompleteDocument);
        	
        	var sendVars:URLVariables = new URLVariables();
    		sendVars.docName = this.docName;
    			
   			var request:URLRequest = new URLRequest();
   			request.url = ip+"text_load.php";
   			request.data = sendVars;
   				   			
   			loader.load(request);               
             
        }   
        
        private function handleCompleteDocument(event:Event):void{
	   			try{
	   				doc = new XML(event.target.data);	// 문서 하나를 xml로 받는다.
	   				
	   				
	   				// 한 문단씩 변환
	   				for(var i:int =0; i<doc.paragraph.length(); i++){	                
		                currentNum = i+1;           
		                tempRich.text = doc.paragraph[i].korean_text+"";	
		                        
		                loadWordData();      // 한 문단의 단어정보를 받는다.(문단번호 = currentNum)
		                ts.temp1.text += " *"+i+"$* ";   
		                translation();       // 한 문단을 변환한다.
		                 ts.temp1.text += " *"+i+"#* ";   
	            	}	 
	            	
	            	for(i=0; i<myData.length; i++){
						myData2.getItemAt(i).col2 = (String)(myData.getItemAt(i).col2);
					}  				
	   				
	   			}catch(e:TypeError){
	   				
	   			}
  		}
  		
  		public function translation():void {
												
				var iii:int;
				iii=0;
				
				var indexx:int;
				var indexy:int;				
				
				var dataNum:int;
				
				var aStr:String = "";
				var bStr:String = "";
				var eng:String = "";
				
				var tempText:TextArea = new TextArea();
				tempText = tempRich.textArea;
				
				for(dataNum=0; dataNum<myData.length; dataNum++){
					
					aStr = myData2.getItemAt(dataNum).col2;
					bStr = myData.getItemAt(dataNum).col2;
					eng = myData2.getItemAt(dataNum).col1;
					if(aStr.localeCompare(bStr)==0) continue;
					   
					for(i=0; i<wordArray.length; i++){
						wl = (WordLocation)(wordArray.getItemAt(i));
						if(aStr.localeCompare(wl.name)==1) continue;
						//else if(eng.localeCompare(wl.eng)==1)continue;
						
						for(j=wl.getSize()-1;j>0;j--){
							indexx = (int)(wl.sp.getItemAt(j));
							indexy = (int)(wl.ep.getItemAt(j));
							if(tempRich.text.substring(indexx,indexy).localeCompare(aStr)==0){
								if((int)(wl.color.getItemAt(j))==255){
									tempRich.selection.beginIndex = indexx;					
									tempRich.selection.endIndex = indexy;
									
									tempText.setSelection(indexx,indexy);
									
									tempRich.selection.text = bStr;
									
									//tempRich.defaultLinkProtocol
								}
							}	
							tempRich.selection.endIndex = 0;
							tempRich.selection.beginIndex = 0;	
							tempText.setSelection(0,0);
						}	
						wl.name = bStr;	// 갱신
													
					}		
									
				}
				
				docScan();
				
				docUpLoad();
				
				wordUpLoad();	
				
				
			}
			
			private function handleCompleteLoadWord(event:Event):void{
	   			try{
	   				var x:XML = new XML(event.target.data);
	   					   		
		   			var sp:int;
		   			var ep:int;
		   			var color:uint;
		   			
		   			var index:int;
		   			
		   			for(j=0; j<wordArray.length; j++){
						(WordLocation)(wordArray.getItemAt(j)).reset();
					}					
		   			
		   			for(i = 0; i<x.word_info.length(); i++){
		   				index = -1;
		   				for(j=0; j<wordArray.length; j++){
		   					if((WordLocation)(wordArray.getItemAt(j)).eng.localeCompare(x.word_info[i].eng)==0){
		   						index = j;
		   					}
		   				}
		   				if(index>=0){	 
		   									
		   					for(j = 0; j<x.word_info[i].count; j++){
			   					sp = x.word_info[i].word[j].sp;
			   					ep = x.word_info[i].word[j].ep;
			   					color = x.word_info[i].word[j].color;
			   					(WordLocation)(wordArray.getItemAt(index)).addPoint(sp, ep, color);
			   				}
			   			}
			   		}
		   			
	   				
	   			}catch(e:TypeError){
	   				trace("error sdh");
	   			}
	   		}
	   		
	   		public function loadWordData():void{
	   			var loader:URLLoader = new URLLoader();
	   			loader.dataFormat = URLLoaderDataFormat.TEXT;
	   			loader.addEventListener(Event.COMPLETE, handleCompleteLoadWord);
	   			loader.load(new URLRequest(ip+"wordxml/"+
						 this.docName + this.currentNum+
						 ".xml"));	   							
	   		}
	   		
	   		public function docScan():void{
	   			
	   			var wordCount:int;
	   			var searchStart:int;
	   			var k:int;
	   			var str:String = "";
	   			var isColor:uint;
	   			
	   			var sp:int;
	   			var ep:int;
	   			var wordInfoColor:int;
	   			
	   			
	   			ts.temp1.text += "\n *"+wordArray.length+"* "; 
	   			ts.temp1.text +=" asd ";
	   				   			
	   			field.text = tempRich.text;
	   			
	   			ts.temp1.text +="\n 2 ";
	   			
	   			for(j=0; j<wordArray.length; j++){
						
					wordCount = 0;   
					wl = (WordLocation)(wordArray.getItemAt(j));
					
					
					
					for(i=0; i<wl.getSize(); i++){
						wl.search.setItemAt(false,i);
					}
					
					
											
					searchStart = 0;	// 본문에서의 l부터 검색을 시작한다.
					k = 0;	// 검색후의 단어의 시작위치. 검색실패시 = -1
					
					str = wl.name;						
					
					while(k!=(-1)){
						k = field.text.indexOf(str,searchStart);	
						tempRich.selection.beginIndex = k;		
						tempRich.selection.beginIndex = k;			
						tempRich.selection.endIndex = k+str.length;
						tempRich.selection.endIndex = k+str.length;	
												
						searchStart = k+ str.length;
						
						// 만약 단어를 찾았다면.
						if(k>=0){
							
							wordInfoColor = (int)(wl.color.getItemAt(wordCount));
								
							wl.sp.setItemAt(k,wordCount);
							wl.ep.setItemAt(k+str.length,wordCount);
								
							wl.search.setItemAt(true, wordCount);	
													
							wordCount++;
						}
					}
											
					for(i=0; i<wl.getSize(); i++){
						if(!wl.isSearch(i)){
							wl.deletPointAt(i);
						}
					}
						
				}
	   		}
	   		
	   		public function docUpLoad():void{
	   			
	   			if(currentNum < 0) return;
	   			
	   			var wts:WordToSvr = new WordToSvr(docName, currentNum, wordArray);
	   			wts.wordSend();
	   			
	   			var sendVars:URLVariables = new URLVariables();
	    		sendVars.name = docName;
	    		sendVars.num = currentNum;
	    		sendVars.text = tempRich.text;
	    		
		    	var request:URLRequest = new URLRequest(ip+"update_paragraph.php");
		    	request.data = sendVars;
		    	
				request.method = URLRequestMethod.POST;
					
				var loader:URLLoader = new URLLoader();
				
				loader.load(request);
				
	   		}
	   		
	   		public function wordUpLoad():void{
	   			
	   		}

	}
}